/*
Copyright 2010 Johan Maasing

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package nu.zoom.catonine.xml;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import nu.zoom.catonine.stylerule.StyleRulesManager;

/**
 * Helper methods to serialize a set of styling rules to a file.
 * 
 * @author "Johan Maasing" &lt;johan@zoom.nu&gt;
 */
public final class StyleRulesManagerPersistence {
	public static final void save(final StyleRulesManager manager, final File file) throws IOException, JAXBException {
		JAXBContext jc = JAXBContext.newInstance(StyleRulesManager.class);
		Marshaller marshaller = jc.createMarshaller();
		marshaller.setProperty("jaxb.formatted.output", true);
		marshaller.marshal(manager, file);
	}

	public static final StyleRulesManager readManager(File managerFile) throws FileCanNotBeReadException,
			JAXBException, FileNotFoundException, IOException, ClassNotFoundException {
		final StyleRulesManager newManager;
		if (!managerFile.exists()) {
			throw new FileNotFoundException("Style rules manager file: " + managerFile + " does not exist");
		} else if (!managerFile.canRead()) {
			throw new FileCanNotBeReadException("Unable to read file: " + managerFile);
		} else {
			if (managerFile.getName().endsWith("xml")) {
				// Use JAXB-format
				JAXBContext jc = JAXBContext.newInstance(StyleRulesManager.class);
				Unmarshaller unmarshaller = jc.createUnmarshaller();
				newManager = (StyleRulesManager) unmarshaller.unmarshal(managerFile);
			} else {
				// Old school serialized manager
				ObjectInputStream objIns = new ObjectInputStream(new FileInputStream(managerFile));
				newManager = (StyleRulesManager) objIns.readObject();
			}
		}
		return newManager;
	}

	public static class FileCanNotBeReadException extends Exception {
		private static final long serialVersionUID = 1L;

		public FileCanNotBeReadException(String message) {
			super(message);
		}
	}

}
